package com.tcp;


import com.domain.CarDevice;
import com.util.JDBCUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 吴总测试  TCP 请求服务端
 * @author: JYao
 * @create: 2021/01/18 20:05
 */

// AccessKey ID       LTAI4G3sFN8xUvNgh7o6ZkWy
// AccessKey Secret   jTsQ3BhEumSYwTcsqPQqR3x5EJYoIz
public class AliTask {
    public static void main(String[] args){
        try {
            Connection conn= JDBCUtil.getConnection();
            tcp(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void tcp(Connection conn) throws Exception {
            CarDevice carDevice=new CarDevice();
            System.out.println("准备");
            // 建立tcp服务端 并且监听一个端口
            ServerSocket serverSocket = new ServerSocket(8883);
            // 获取输出流对象 读取客户端发来的数据
            // 1,获取输入对象
            // 2,accept()接受客户端链接 没有链接时会一直等待 程序不会往下执行
            Socket socket = serverSocket.accept();
            System.out.println("监听到链接,开始");
            // 3,获取输入流对象 读取内容
            InputStream inputStream = socket.getInputStream();
            byte[] buf = new byte[1024];
            int length = 0;
            length = inputStream.read(buf);
            //转为字符    (HC:***,**,**)
            String hc=new String(buf, 0, length);
            System.out.println("服务器端收到:" + hc);
            //去掉前三个字符
            hc=hc.substring(3);
            System.out.println("截取字符:" + hc);
            //根据,拆分
            String[] hcs=hc.split(",");
            carDevice.setDevice(hcs[0]);
            carDevice.setAp(hcs[1]);
            carDevice.setKilometers(hcs[2]);
            System.out.println(carDevice.getDevice());
            System.out.println(carDevice.getAp());
            System.out.println(carDevice.getKilometers());
            if(Sql.select(carDevice.getDevice(),conn).equals("")){
                System.out.println("insert");
                Sql.insert(carDevice,conn);
            }else{
                System.out.println("update");
                Sql.update(carDevice,conn);
            }
            //客户端与服务器端交互
            OutputStream outputStream = socket.getOutputStream();
            //返回给客户端信息
            String data = "123";
            outputStream.write(data.getBytes());
            // 关闭资源
            serverSocket.close();
            System.out.println("结束");
        System.out.println("");
        //重新启动
        tcp(conn);
    }


}
